vim9script noclear

var winid: number = 0
var bufid: number = 0
var col = &columns > 130 ? 30 : 25
var width: number = float2nr((&columns - col) * 0.7)
var height: number = float2nr(&lines * 0.6)

def TerminalOpen(): void
	winid = popup_create(bufid, 
	{
		tabpage: -1,
		minwidth: width,
		maxwidth: width,
		minheight: height,
		maxheight: height,
		highlight:  'Normal',
		borderhighlight: ['FloatermBorder'],
		border: [1, 1, 1, 1],
		borderchars: ['─', '│', '─', '│', '┌', '┐', '┘', '└']
	})
enddef

def TerminalClose(): void
	popup_close(winid)
	winid = 0
enddef

export def TerminalToggle(): void
	if bufid == 0
		width = float2nr((&columns - col) * 0.7)
		height = float2nr(&lines * 0.6)
		bufid = term_start(&shell, {
			hidden: 1,
			term_finish: 'close',
			exit_cb: (job, status) => {
				popup_close(winid)
				winid = 0
				bufid = 0
			}
		})
	endif

	((winid == 0) && empty(win_gettype())) ? TerminalOpen() : TerminalClose()
enddef

export def TerminalAutoClose(): void
	(winid == 0) ?? TerminalClose()
enddef
